<template>
  <div ref="echartsInstance" class="echarts"></div>
</template>

<script setup>
import * as echarts from "echarts";
import { onMounted, ref } from "vue";

const { option } = defineProps({
  option: {
    type: Object,
    required: true,
  },
});

const echartsInstance = ref(null);
let myChart = null;

onMounted(() => {
  if (option) {
    myChart = echarts.init(echartsInstance.value);
    // set options here
    myChart.setOption(option);
  }
});

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
});

watch(
  () => option,
  (newVal) => {
    if (myChart) {
      myChart.setOption(newVal);
    }
  },
  {
    deep: true,
  },
);

// resize chart when window is resized
// window.onresize = () => {
//   if (myChart) {
//     myChart.resize();
//   }
// };

window.addEventListener(
  "onorientationchange" in window ? "orientationchange" : "resize",
  () => {
    if (myChart) {
      myChart.resize();
    }
  },
);
</script>

<style scoped lang="scss">
.echarts {
  flex: 1;
  width: 100%;
  height: 100%;
}
</style>
